from PyQt5 import QtWidgets, QtCore
from PyQt5.QtWidgets import *
from interface import Ui_MainWindow
from threads import *
import sys, qdarkstyle
from datetime import datetime


class Free_Ui(QtWidgets.QMainWindow, Ui_MainWindow):
    def __init__(self, parent=None):
        super(Free_Ui, self).__init__(parent)
        self.setupUi(self)
        # 运行时需要的变量
        self.files = []
        self.pages = []
        # 初始化设置一些widget
        self.label_4.setVisible(False)
        self.label_6.setVisible(False)
        self.label_7.setVisible(False)
        self.pushButton_3.setVisible(False)
        self.progressBar.setVisible(False)
        self.lineEdit.setPlaceholderText("仅使用PDF合并功能时可填写")
        self.lineEdit.setReadOnly(True)
        # 默认选择的功能是PDF转word
        self.checkBox.setChecked(True)
        self.comboBox.addItems(['原文件相同目录', '自定义目录'])
        self.initTable()

        # 绑定功能
        self.checkBox.clicked.connect(self.toPDF)
        self.checkBox_2.clicked.connect(self.toWord)
        self.checkBox_3.clicked.connect(self.pdfExtract)
        self.checkBox_4.clicked.connect(self.pdfMerge)
        self.pushButton.clicked.connect(self.addFiles)
        self.pushButton_2.clicked.connect(self.clearTable)
        self.pushButton_3.clicked.connect(self.selectPath)
        self.pushButton_4.clicked.connect(self.export)
        self.pushButton_5.clicked.connect(self.selectAll)
        self.pushButton_6.clicked.connect(self.selectNone)
        self.comboBox.currentIndexChanged.connect(self.comboBoxFunc)
    
    def toPDF(self):
        # 将程序的功能设定为Word转PDF
        self.checkBox.setChecked(True)
        self.checkBox_2.setChecked(False)
        self.checkBox_3.setChecked(False)
        self.checkBox_4.setChecked(False)
        self.lineEdit.setReadOnly(True)
        self.label_7.setVisible(False)
        self.clearTable()
    
    def toWord(self):
        # 将程序的功能设定为Word转PDF
        self.checkBox.setChecked(False)
        self.checkBox_2.setChecked(True)
        self.checkBox_3.setChecked(False)
        self.checkBox_4.setChecked(False)
        self.lineEdit.setReadOnly(True)
        self.label_7.setVisible(False)
        self.clearTable()
    
    def pdfExtract(self):
        # 将程序的功能设定为PDF拆分
        self.checkBox.setChecked(False)
        self.checkBox_2.setChecked(False)
        self.checkBox_3.setChecked(True)
        self.checkBox_4.setChecked(False)
        self.lineEdit.setReadOnly(True)
        self.label_7.setVisible(False)
        self.clearTable()
    
    def pdfMerge(self):
        # 将程序的功能设定为PDF合并
        self.checkBox.setChecked(False)
        self.checkBox_2.setChecked(False)
        self.checkBox_3.setChecked(False)
        self.checkBox_4.setChecked(True)
        self.lineEdit.setReadOnly(False)
        self.label_7.setVisible(False)
        self.clearTable()
    
    def comboBoxFunc(self):
        if self.comboBox.currentText() == self.comboBox.itemText(0):
            self.label_4.setVisible(False)
            self.pushButton_3.setVisible(False)
        elif self.comboBox.currentText() == self.comboBox.itemText(1):
            self.label_4.setText("")
            self.label_4.setVisible(True)
            self.pushButton_3.setVisible(True)
    
    def selectPath(self):
        outputDirectory = QtWidgets.QFileDialog.getExistingDirectory()
        self.label_4.setText(outputDirectory)
    
    def initTable(self):
        self.tableWidget.clearContents()
        self.tableWidget.setRowCount(0)
        self.tableWidget.setColumnCount(3)
        # self.tableWidget.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)  # 自适应宽度
        # 手动设置各列宽度
        self.tableWidget.setColumnWidth(0, 35)
        self.tableWidget.setColumnWidth(1, 500)
        self.tableWidget.setColumnWidth(2, 100)
        self.tableWidget.horizontalHeader().setVisible(True)
        self.tableWidget.setHorizontalHeaderLabels(['选择', '文件路径', '操作'])
        self.tableWidget.setEditTriggers(QAbstractItemView.NoEditTriggers)  # 设置表格内容不可编辑
    
    def initTable_pdfExtract(self):
        self.tableWidget.clearContents()
        self.tableWidget.setRowCount(0)
        self.tableWidget.setColumnCount(5)
        # self.tableWidget.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)  # 自适应宽度
        # 手动设置各列宽度
        self.tableWidget.setColumnWidth(0, 35)
        self.tableWidget.setColumnWidth(1, 285)
        self.tableWidget.setColumnWidth(2, 45)
        self.tableWidget.setColumnWidth(3, 220)
        self.tableWidget.setColumnWidth(4, 55)
        self.tableWidget.horizontalHeader().setVisible(True)
        self.tableWidget.setHorizontalHeaderLabels(['选择', '文件路径', '页数', '输出范围', '操作'])
        self.tableWidget.setEditTriggers(QAbstractItemView.NoEditTriggers)  # 设置表格内容不可编辑
    
    def clearTable(self):
        if self.checkBox_3.isChecked() == True:
            self.tableWidget.clearContents()
            self.tableWidget.setRowCount(0)
            self.tableWidget.setColumnCount(5)
            self.initTable_pdfExtract()
        else:
            self.tableWidget.clearContents()
            self.tableWidget.setRowCount(0)
            self.tableWidget.setColumnCount(3)
            self.initTable()
    
    def deleteButtom(self):
        widget = QtWidgets.QWidget()
        # 删除
        self.deletePersonBtn = QtWidgets.QPushButton('删除')
        self.deletePersonBtn.setStyleSheet(''' text-align : center;
                                    background-color : LightCoral;
                                    height : 30px;
                                    border-style: outset;
                                    font : 12px; ''')
        self.deletePersonBtn.clicked.connect(self.deleteButtonFunc)
        hLayout = QtWidgets.QHBoxLayout()
        hLayout.addWidget(self.deletePersonBtn)
        hLayout.setContentsMargins(5, 2, 5, 2)
        widget.setLayout(hLayout)
        return widget
    
    def deleteButtonFunc(self):
        button = self.sender()
        if button:
            row = self.tableWidget.indexAt(button.parent().pos()).row()
            self.tableWidget.removeRow(row)
    
    def addFiles(self):
        """
        在列表中添加一个文件或多个文件
        """
        if self.checkBox.isChecked() == True:
            self.files, _ = QtWidgets.QFileDialog.getOpenFileNames(self, "选取文件", "", "DOCX Files (*.docx);;DOC Files(*.doc)")
        else:
            self.files, _ = QtWidgets.QFileDialog.getOpenFileNames(self, "选取文件", "", "PDF Files (*.pdf)")
        if self.files == []:
            return
        if self.checkBox_3.isChecked() == True:
            for i in range(len(self.files)):
                row = self.tableWidget.rowCount()
                self.tableWidget.setRowCount(row + 1)
                self.tableWidget.setCellWidget(row, 0, QCheckBox())
                # 添加时默认是选中的
                self.tableWidget.cellWidget(row, 0).setChecked(True)
                self.tableWidget.setItem(row, 1, QTableWidgetItem(self.files[i]))
                self.tableWidget.item(row, 1).setTextAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
                self.tableWidget.setItem(row, 2, QTableWidgetItem(getPageNum(self.files[i])))
                self.tableWidget.item(row, 2).setTextAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
                line = QLineEdit()
                line.setPlaceholderText("示例: 2,3-5,7-9 (不填表示全选)")
                self.tableWidget.setCellWidget(row, 3, line)
                self.tableWidget.setCellWidget(row, 4, self.deleteButtom())
                self.tableWidget.resizeRowsToContents()
        else:
            for i in range(len(self.files)):
                row = self.tableWidget.rowCount()
                self.tableWidget.setRowCount(row + 1)
                self.tableWidget.setCellWidget(row, 0, QCheckBox())
                # 添加时默认是选中的
                self.tableWidget.cellWidget(row, 0).setChecked(True)
                self.tableWidget.setItem(row, 1, QTableWidgetItem(self.files[i]))
                self.tableWidget.item(row, 1).setTextAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
                self.tableWidget.setCellWidget(row, 2, self.deleteButtom())
                self.tableWidget.resizeRowsToContents()
    
    def selectAll(self):
        if self.tableWidget.rowCount() != 0:
            for i in range(self.tableWidget.rowCount()):
                self.tableWidget.cellWidget(i, 0).setChecked(True)
    
    def selectNone(self):
        if self.tableWidget.rowCount() != 0:
            for i in range(self.tableWidget.rowCount()):
                self.tableWidget.cellWidget(i, 0).setChecked(False)
    
    def updateFiles(self):
        """
        导出操作中使用, 更新文件列表, 仅包含被选中的文件
        """
        self.files.clear()
        if self.tableWidget.rowCount() != 0:
            for i in range(self.tableWidget.rowCount()):
                if self.tableWidget.cellWidget(i, 0).isChecked() == True:
                    self.files.append(self.tableWidget.item(i, 1).text())
    
    def updatePages(self):
        self.pages.clear()
        if self.tableWidget.rowCount() != 0:
            for i in range(self.tableWidget.rowCount()):
                if self.tableWidget.cellWidget(i, 0).isChecked() == True:
                    if self.tableWidget.cellWidget(i, 3).text() == "":
                        pageNum = self.tableWidget.item(i, 2).text()
                        self.pages.append(f"1-{pageNum}")
                    else:
                        self.pages.append(self.tableWidget.cellWidget(i, 3).text())
    
    def export(self):
        self.updateFiles()
        if self.files == []:
            return
        if self.checkBox.isChecked() == True:
            # Word转PDF
            # 检查平台
            if sys.platform == "darwin" or sys.platform == "win32":
                if self.comboBox.currentText() == "原文件相同目录" or (self.comboBox.currentText() == "自定义目录" and self.label_4.text() == ""):
                    self.label_6.setVisible(True)
                    self.progressBar.setValue(int(0))
                    self.progressBar.setVisible(True)
                    self.t = Word2PDFThread(self.files, exportPath="")
                    self.t.transStatus.connect(self.barSignalCallback)
                    self.t.start()
                else:
                    # 指定了目录
                    exportPath = self.label_4.text()
                    self.label_6.setVisible(True)
                    self.progressBar.setValue(int(0))
                    self.progressBar.setVisible(True)
                    self.t = Word2PDFThread(self.files, exportPath=exportPath)
                    self.t.transStatus.connect(self.barSignalCallback)
                    self.t.start()
            else:
                self.label_7.setText("此功能暂不支持Linux系统！")
                self.label_7.setVisible(True)
        elif self.checkBox_2.isChecked() == True:
            # PDF转WORD
            if self.comboBox.currentText() == "原文件相同目录" or (self.comboBox.currentText() == "自定义目录" and self.label_4.text() == ""):
                self.label_6.setVisible(True)
                self.progressBar.setValue(int(0))
                self.progressBar.setVisible(True)
                self.t = PDF2WordThread(self.files, exportPath="")
                self.t.transStatus.connect(self.barSignalCallback)
                self.t.start()
            else:
                # 指定了目录
                exportPath = self.label_4.text()
                self.label_6.setVisible(True)
                self.progressBar.setValue(int(0))
                self.progressBar.setVisible(True)
                self.t = PDF2WordThread(self.files, exportPath=exportPath)
                self.t.transStatus.connect(self.barSignalCallback)
                self.t.start()
        elif self.checkBox_3.isChecked() == True:
            # PDF提取
            self.updatePages()
            if self.comboBox.currentText() == "原文件相同目录" or (self.comboBox.currentText() == "自定义目录" and self.label_4.text() == ""):
                self.label_6.setVisible(True)
                self.progressBar.setValue(int(0))
                self.progressBar.setVisible(True)
                self.t = PDFExtractThread(self.files, self.pages, exportPath="")
                self.t.transStatus.connect(self.barSignalCallback)
                self.t.start()
            else:
                # 指定了目录
                exportPath = self.label_4.text()
                self.label_6.setVisible(True)
                self.progressBar.setValue(int(0))
                self.progressBar.setVisible(True)
                self.t = PDFExtractThread(self.files, self.pages, exportPath=exportPath)
                self.t.transStatus.connect(self.barSignalCallback)
                self.t.start()
        elif self.checkBox_4.isChecked() == True:
            # PDF合并
            if self.comboBox.currentText() == "原文件相同目录" or (self.comboBox.currentText() == "自定义目录" and self.label_4.text() == ""):
                self.label_6.setVisible(True)
                self.progressBar.setValue(int(0))
                self.progressBar.setVisible(True)
                if self.lineEdit.text() == "":
                    filename = str(datetime.now().strftime("%y%m%d%H%M%S")) + "合并.pdf"
                else:
                    filename = self.lineEdit.text() + ".pdf"
                self.t = PDFMerge(self.files, exportPath="", fileName=filename)
                self.t.transStatus.connect(self.barSignalCallback)
                self.t.start()
            else:
                # 指定了目录
                exportPath = self.label_4.text()
                self.label_6.setVisible(True)
                self.progressBar.setValue(int(0))
                self.progressBar.setVisible(True)
                if self.lineEdit.text() == "":
                    filename = str(datetime.now().strftime("%y%m%d%H%M%S")) + "合并.pdf"
                else:
                    filename = self.lineEdit.text() + ".pdf"
                self.t = PDFMerge(self.files, exportPath=exportPath, fileName=filename)
                self.t.transStatus.connect(self.barSignalCallback)
                self.t.start()
    
    def barSignalCallback(self, i):
        """
        更改进度条信息
        """
        self.progressBar.setValue(int(i / len(self.files) * 100))
        if int(i / len(self.files) * 100) == 100:
            self.progressBar.setVisible(False)
            self.label_6.setVisible(False)


if __name__ == "__main__":
    import sys
    QtCore.QCoreApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling)
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = Free_Ui()
    app.setStyleSheet(qdarkstyle.load_stylesheet(qt_api='pyqt5'))
    MainWindow.show()
    sys.exit(app.exec_())